<script lang="ts" setup name="SelectTable">
import { ColumnProps, ProTableInstance } from '../ProTable/interface'

interface DialogProps {
  isView: boolean
  title: string
  selTags?: any
  columns: ColumnProps[]
  idName?: string
  mate?: string
  apiParams: {}
  api?: (params: any) => Promise<any>
  selType?: 'selection' | 'radio'
  width?: number | string
  index?: number
}
interface Emits {
  (name: 'radio', value: any): void
  (name: 'selectedList', value: any): void
}

const dialogProps = ref<DialogProps>({
  isView: false,
  selType: 'selection',
  title: '',
  mate: 'id',
  apiParams: {},
  width: 600,
  columns: [],
})

const proTableRef = ref<ProTableInstance>()
const initParam = ref({}) // 搜索数据
const dialogVisible = ref(false)
const tableData = ref<any[]>([])
const tags = ref<any>([])
const emit = defineEmits<Emits>()

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  dialogProps.value = params
  dialogProps.value.selType = params.selType || 'selection'
  tags.value = dialogProps.value.selTags
  await getTableData()
  dialogVisible.value = true
}

const setInitParams = (params: any) => {
  initParam.value = params
  getTableData()
}

const getTableData = () => {
  tableData.value = []
  dialogProps.value!.api!({
    pageNum: 1,
    pageSize: 9999,
    ...dialogProps.value.apiParams,
    ...initParam.value,
  })
    .then((res) => {
      // 处理数据
      tableData.value = JSON.parse(JSON.stringify(res.data.list ? res.data.list : res.data)) ?? []
      if (dialogProps.value.selType === 'selection') {
        nextTick(() => {
          // const tags_Ids = tags.value.map(i => i.id);
          if (dialogProps.value.mate) {
            // 先判断mate不是undefined
            const tags_Ids = tags.value.map((i: any) => i.id)
            tableData.value.forEach((item) => {
              if (tags_Ids.includes(item[dialogProps.value.mate as keyof typeof item])) {
                proTableRef.value!.element!.toggleRowSelection(item, true)
              }
            })
          }
        })
      }
      if (dialogProps.value.selTags && dialogProps.value.selType === 'radio') {
        proTableRef.value?.setRadio(tableData.value.find((item) => item.id === dialogProps.value.selTags))
      }
    })
    .catch(() => {
      tableData.value = []
    })
}

const changeSelection = (selection: any[]) => {
  tags.value = selection
}

// 提交数据（选择菜品）
const onEmit = () => {
  if (dialogProps.value.selType === 'radio') {
    emit('radio', { data: proTableRef.value!.radio })
  } else if (dialogProps.value.selType === 'selection') {
    emit('selectedList', {
      list: tags.value,
      title: dialogProps.value.title,
    })
  }
  dialogVisible.value = false
}

defineExpose({
  acceptParams,
  setInitParams,
})
</script>

<template>
  <vab-dialog v-model:modelValue="dialogVisible" destroy-on-close :title="dialogProps.title" :width="dialogProps.width">
    <div class="selector-container">
      <slot name="input"></slot>
      <div class="table-box">
        <pro-table
          ref="proTableRef"
          :columns="dialogProps.columns"
          :data="tableData"
          :indent="20"
          :margin-border="false"
          :max-height="280"
          :pagination="false"
          :row-key="dialogProps.mate"
          :tool-button="false"
          @selection-change="changeSelection"
        />
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onEmit">确定</el-button>
    </template>
  </vab-dialog>
</template>

<style lang="scss" scoped>
@use './index.scss';
</style>
